<script lang="ts" setup>
import { ElMessage, ElTable } from "element-plus"
import { ref } from "vue"
import { VXETable, VxeGridInstance, VxeGridProps, VxeGridListeners } from "vxe-table"
import dayjs from "dayjs";


let currentPage = ref(1)
let pageSize = ref(10)
let size = 'default'
let total = ref(0)
interface RowVO {
  id: number
  name: string
  nickname: string
  role: string
  sex: string
  age: number
  address: string
}
let filterKeywords = ref('')

/* changeFilterEvent
 用于vxe-table 筛选时间的输入内容的接受和激活筛选按钮
 option.data： 输入框值
 $panel 弹出面板
*/
const changeFilterEvent = (event, option, $panel) => {
  $panel.changeOption(event, !!option.data, option)
  filterKeywords.value = option.data
}

/* 表头过滤函数 */
const runNameFilter = ({ row }) => {
  return row.runName.includes(filterKeywords.value)
}
let { proxy } = getCurrentInstance() as any
const router = useRouter()
let formInline = ref({ runName: "" })
let params = {
  runName: '',
  pageNo: currentPage.value,
  pageSize: pageSize.value,
  isAsc: false,
  orderBy: "startTime"
}
let showRowDetails = ref(false)
//  这里的配置是 vve-table 配置式渲染的json 文档：https://vxetable.cn/v4/#/component/grid/base/basic
const xGrid = ref<VxeGridInstance<RowVO>>()
const gridOptions = reactive<VxeGridProps<RowVO>>({
  border: true,
  keepSource: true,
  id: "toolbar_demo_1",
  height: 630,
  printConfig: {},
  importConfig: {},
  exportConfig: {},
  columnConfig: {
    resizable: true
  },
  customConfig: {
    storage: true
  },
  editConfig: {
    trigger: "dblclick",
    mode: "row",
    showStatus: true
  },
  columns: [
    { type: "checkbox", width: 50 },
    { type: "seq", width: 60 },
    { field: "runId", title: "模型id", sortable: false, editRender: {} },
    { field: "runName", title: "模型名称", sortable: false, showOverflow: true, editRender: {}, slots: { filter: 'runName_filter' }, filters: [{ data: '' }], filterMethod: runNameFilter },
    { field: "description", title: "模型描述", sortable: false, showOverflow: true, editRender: {}, },
    { field: "createTime", title: "创建时间", sortable: true, formatter: ({ cellValue }) => { return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss') }, showOverflow: true, editRender: {}, },
    { field: "duration", title: "持续时间", sortable: false, showOverflow: true, editRender: {}, },
    { field: "status", title: "状态", sortable: false, showOverflow: true, editRender: {}, },
    { field: "startTime", title: "开始时间", sortable: false, showOverflow: true, editRender: {}, },
    { field: "endTime", title: "结束时间", sortable: false, showOverflow: true, editRender: {}, },
    { field: "lifecycleStage", title: "操作", sortable: false, showOverflow: true, editRender: {}, }
  ],
  toolbarConfig: {
    buttons: [{ code: "delete", name: "删除" }],
    import: true,
    export: true,
    print: true,
    zoom: true,
    custom: true
  },
  data: []
})
// vxe-table 配置式表格的事件定义
const gridEvents: VxeGridListeners<RowVO> = {
  toolbarButtonClick({ code }) {
    const $grid = xGrid.value
    let x = 0
    if ($grid) {
      switch (code) {
        case "delete": {
          const selectRows = $grid.getCheckboxRecords();
          if (selectRows) {
            selectRows.forEach(s => {
              proxy.$http.delete(`/admin-api/wpes/runResult/delete?id=${s.id}`).then((v) => {
                if (v.data.code == 0) {
                  x++
                  if (x == selectRows.length) {
                    onSubmit()
                    ElMessage.success('删除成功！')
                  }
                }
              })
            })


          }
          break
        }
        case "mySave": {
          const { insertRecords, removeRecords, updateRecords } = $grid.getRecordset()
          VXETable.modal.message({
            content: `新增 ${insertRecords.length} 条，删除 ${removeRecords.length} 条，更新 ${updateRecords.length} 条`,
            status: "success"
          })
          break
        }
        case "myExport": {
          $grid.exportData({
            type: "csv"
          })
          break
        }
      }
    }
  },
  toolbarToolClick({ code }) {
    const $grid = xGrid.value
    if ($grid) {
      switch (code) {
        case "myPrint": {
          $grid.print()
          break
        }
      }
    }
  }
}
let runDetails = ref([] as any)
const chongzhi = () => {
  formInline.value.runName = ''
  params.runName = formInline.value.runName
  onSubmit()
}

const onSubmit = () => {
  let url = "/admin-api/wpes/runResult/page"
  params.runName = formInline.value.runName
  proxy.$http.get(url, { params }).then((v) => {
    if (v.data.code == 0) {
      total.value = v.data.data.total
      gridOptions.data = v.data.data.list
    }
  })
}
const getRowDataByClick = (row) => {
  // /admin-api/wpes/bpnnRun/getDetails /ai/bp-service/getBpnnRun/
  let url = "/admin-api/wpes/runResult/get"
  console.log(row)
  let id = row.row.id
  let status = row.row.status
  let params = {
    id,
  }
  console.log(status)
  proxy.$http.get(url, { params }).then((v) => {
    if (v.data.code == 0) {
      console.log(v.data.data)
      const { href } = router.resolve({
        path: "/runDetails/index",
        query: {
          rowData: JSON.stringify(v.data.data)
        }
      })
      if (status == 'FINISHED' || status == 'STOPPED') {
        window.open(href, "_blank")
      } else if (status == 'WAITING') {
        ElMessage.warning('本次运行结果未完成，无法查看')
      } else if (status == 'FAILED') {
        ElMessage.warning('本次运行结果有错误，无法查看！')
      } else if (status == 'RUNNING') {
        // 如果是running状态，点击跳转到训练页面，参数是之前选择的参数
        const { href } = router.resolve({
          path: "/modelTrain/index",
          query: {
            rowData: JSON.stringify(v.data.data)
          }
        })
        window.open(href, "_blank")
      }
      else if (status == 'ERROR') {
        ElMessage.warning(`${v.data.data.errorMsg}`)
      }
    }
    else {
      ElMessage.warning('本次运行结果有错误，无法查看！')
    }
  }).catch(() => {
    ElMessage.warning('本次运行结果有错误，无法查看！')
  })
}

const handleCurrentChange = (e) => {
  params.pageNo = e
  onSubmit()
}
onMounted(() => {
  onSubmit()
})

</script>

<template>
  <div class="css_cx">
    <div class="css_cxc">
      <!--  @submit.native.prevent 阻止enter 刷新页面-->
      <el-form :inline="true" @submit.native.prevent :model="formInline" style="margin: 20px 10px"
        class="demo-form-inline">
        <el-form-item label="模型名称：">
          <el-input :maxlength="15" v-model="formInline.runName" placeholder="请输入模型名称：" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button type="primary" @click="chongzhi">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- el-dialog -->

      <el-dialog v-model="showRowDetails" title="数据集选择">
        <el-table :data="runDetails" @row-click="">
          <el-table-column align="center" property="createTime" label="创建日期" width="150" />
          <el-table-column align="center" property="dataName" label="板材型号" width="200" />
          <el-table-column align="center" property="dataThickness" label="板材厚度" />
          <el-table-column align="center" property="dataSize" label="数据集数量" />
          <el-table-column align="center" property="inputParamNum" label="输入参数" />
          <el-table-column align="center" property="outParamNum" label="输出参数" />
          <el-table-column align="center" property="oldFileName" label="数据集" />
        </el-table>
      </el-dialog>

      <!-- 列表 -->
      <div>
        <vxe-grid @cell-click="getRowDataByClick" ref="xGrid" v-bind="gridOptions" v-on="gridEvents">
          <template #runName_filter="{ column, $panel }">
            <div>
              <div v-for="(option, index) in column.filters" :key="index">
                <input type="type" v-model="option.data" @input="changeFilterEvent($event, option, $panel)" />
              </div>
            </div>
          </template>

        </vxe-grid>
      </div>
    </div>
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :size="size" :disabled="false"
      :background="true" layout="prev, pager, next, jumper" :total="total" @current-change="handleCurrentChange" />
  </div>
</template>

<style scoped lang="scss">
@import "@/styles/modelManage.scss";
</style>
